<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\dao\property\auth;

use app\common\repositories\property\auth\PropertyAuthAccessRepository;
use think\db\BaseQuery;
use app\common\dao\BaseDao;
use app\common\model\property\auth\PropertyAuthRoleModel;

class PropertyAuthRoleDao extends BaseDao
{

    /**
     * @return PropertyAuthRoleModel
     */
    protected function getModel(): string
    {
        return PropertyAuthRoleModel::class;
    }


    /**
     * @param array $where
     * @return BaseQuery
     */
    public function search(array $where, int $userId = null)
    {
        return $this->getModel()::getDB()
            ->when($userId !== null, function ($query) use ($userId) {
                /** @var PropertyAuthAccessRepository $propertyAuthAccessRepository */
                $propertyAuthAccessRepository = app()->make(PropertyAuthAccessRepository::class);
                $propertyIds = $propertyAuthAccessRepository->getPropertyIdsByUserId($userId);
                $query->where('property_id', 'in', $propertyIds);
            })
            ->when(isset($where['property_id']) && $where['property_id'] !== '', function ($query) use ($where) {
                $query->where('property_id', intval($where['property_id']));
            })
            ->when(isset($where['keywords']) && $where['keywords'] !== '', function ($query) use ($where) {
                $query->whereLike('name|remark', '%' . trim($where['keywords']) . '%');
            })
            ->when(isset($where['add_time']) && $where['add_time'] !== '', function ($query) use ($where) {
                $this->timeSearchBuild($query, $where['add_time'], 'add_time');
            });
    }


}
